package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.dto.ApplicationAddDTO;
import com.xbongbong.paas.pojo.dto.ApplicationCopyDTO;
import com.xbongbong.paas.pojo.dto.ApplicationDelDTO;
import com.xbongbong.paas.pojo.dto.ApplicationListDTO;
import com.xbongbong.paas.pojo.dto.ApplicationSortDTO;
import com.xbongbong.paas.pojo.dto.ApplicationUpdateDTO;
import com.xbongbong.paas.pojo.dto.CheckAllowRollBackDTO;
import com.xbongbong.paas.pojo.dto.EnableApplicationListDTO;
import com.xbongbong.paas.pojo.vo.ApplicationAddVO;
import com.xbongbong.paas.pojo.vo.ApplicationCopyVO;
import com.xbongbong.paas.pojo.vo.ApplicationDelVO;
import com.xbongbong.paas.pojo.vo.ApplicationListVO;
import com.xbongbong.paas.pojo.vo.ApplicationSortVO;
import com.xbongbong.paas.pojo.vo.ApplicationUpdateVO;
import com.xbongbong.paas.pojo.vo.CheckAllowRollBackVo;
import com.xbongbong.paas.pojo.vo.EnableApplicationListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.app.pojo.dto.HasFormDataDTO;
import com.xbongbong.pro.app.pojo.vo.HasFormDataVO;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 应用管理接口
 *
 * @author kaka
 * @time 2018-7-30 14:07
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/app")
public class PaasAppController {

    private static final Logger LOG = LoggerFactory.getLogger(PaasAppController.class);

    @Resource
    private PaasAppService paasAppService;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    /**
     * 增加应用
     * @param applicationAddDTO
     * @param br
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid ApplicationAddDTO applicationAddDTO, BindingResult br, HttpServletRequest request) throws Exception {
        XbbResponse<ApplicationAddVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
            LOG.info("========================addPaasApp========================" + errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(applicationAddDTO.getIgnoreConCheck())) {
                LOG.info("========================addPaasApp========================" + applicationAddDTO.getIgnoreConCheck());
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(applicationAddDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    LOG.info("========================addPaasApp========================" + JSON.toJSONString(response));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                LOG.info("========================paasAppService.addPaasApp========================");
                ApplicationAddVO applicationAddVO = paasAppService.addPaasApp(applicationAddDTO);
                response = new XbbResponse<>(applicationAddVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 根据对象applicationListDTO中的corpid 公司id查询对应的应用
     * @author wufeng
     * @date 2018/8/29 16:21
     * @param applicationListDTO
     * @param br
     * @descption
     * @return java.lang.String
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid ApplicationListDTO applicationListDTO, BindingResult br) throws Exception {
        XbbResponse<ApplicationListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ApplicationListVO applicationListVO = paasAppService.listPaasApp(applicationListDTO);
                response = new XbbResponse<>(applicationListVO, applicationListVO.getAppList().size());
            } catch (XbbException e){
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 删除应用
     * @param applicationDelDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid ApplicationDelDTO applicationDelDTO, BindingResult br) throws Exception {
        XbbResponse<ApplicationDelVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ApplicationDelVO applicationDelVO = this.paasAppService.deletePaasApp(applicationDelDTO);
                response = new XbbResponse<>(applicationDelVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 更新应用
     * @param applicationUpdateDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String update(@RequestBody @Valid ApplicationUpdateDTO applicationUpdateDTO, BindingResult br) throws Exception {
        XbbResponse<ApplicationUpdateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ApplicationUpdateVO applicationUpdateVO = this.paasAppService.updatePaasApp(applicationUpdateDTO);
                response = new XbbResponse<>(applicationUpdateVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 应用排序
     * @param applicationSortDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/sort", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateSort(@RequestBody @Valid ApplicationSortDTO applicationSortDTO, BindingResult br) throws Exception {
        XbbResponse<ApplicationSortVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ApplicationSortVO applicationSortVO = this.paasAppService.updateSort(applicationSortDTO);
                response = new XbbResponse<>(applicationSortVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取启用的的应用列表
     * @param enableApplicationListDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/enableAppList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String userAppList(@RequestBody @Valid EnableApplicationListDTO enableApplicationListDTO, BindingResult br) throws Exception {
        XbbResponse<EnableApplicationListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                EnableApplicationListVO enableApplicationListVO = this.paasAppService.enableAppList(enableApplicationListDTO);
                response = new XbbResponse<>(enableApplicationListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 复制应用
     * @param applicationCopyDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String copy(@RequestBody @Valid ApplicationCopyDTO applicationCopyDTO, BindingResult br) {
        XbbResponse<ApplicationCopyVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ApplicationCopyVO applicationCopyVO = paasAppService.copy(applicationCopyDTO);
                response = new XbbResponse<>(applicationCopyVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 回退校验应用是否有数据
     * @param checkAllowRollBackDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/checkAllowRollBack", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String checkAlloWRollBack(@RequestBody @Valid CheckAllowRollBackDTO checkAllowRollBackDTO, BindingResult br) {
        XbbResponse<CheckAllowRollBackVo> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                CheckAllowRollBackVo checkAllowRollBackVo = paasAppService.checkAllowRollBack(checkAllowRollBackDTO);
                response = new XbbResponse<>(checkAllowRollBackVo);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    /**
     * http://yapi.xbongbong.com/project/87/interface/api/17186
     * @Description: 校验应用或者表单下是否有数据
     * @param otherDataListDTO
     * @return: java.lang.String
     * @author: wufeng
     * @date 2020/3/27 22:05
     */
    @RequestMapping(value = "/hasData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String hasData(@RequestBody @Valid HasFormDataDTO otherDataListDTO, BindingResult br) {
        XbbResponse<HasFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                HasFormDataVO hasData = paasAppService.hasData(otherDataListDTO);
                response = new XbbResponse<>(hasData);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
